package com.sy.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @Author: zx_dong
 * @CreateTime: 2025-04-22
 */
public class HuYiCloudSMS {
    // 互亿无线接口
    private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

    public static String sendSMS(String phone_number) {
        boolean b = false;
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);
        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=GBK");
        int mobile_code = (int)((Math.random()*9+1)*100000);
        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
        NameValuePair[] data = {//提交短信
                new NameValuePair("account", "C74221137"), //查看用户名是登录用户中心->验证码短信->产品总览->APIID
                new NameValuePair("password", "4690fb24e0b64de7f30e5047dffb1f9c"),  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", phone_number),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String SubmitResult = method.getResponseBodyAsString();
            System.out.println(SubmitResult);
            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();
            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            if("2".equals(code)){
                //发送成功后返回发送成功的验证码
                return mobile_code + "";
            }else {
                return null;
            }

        }catch (Exception e) {
            throw new RuntimeException("短信发送异常");
        }
    }

    public static void main(String[] args) {
        String sms = HuYiCloudSMS.sendSMS("17856688824");
        System.out.println(sms);
    }

}
